package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
/**
 * 社交登录
 */
@Slf4j
@Controller
public class Oauth2Controller {
    @Autowired private MemberFeignService memberFeignService;

    /**
     * 社交登录功能(码云测试)
     */
    @GetMapping("/oauth2.0/gitee/success")
    public String authorize(@RequestParam("code") String code, HttpSession session) throws Exception {
        //1、使用 code 换取 token，换取成功则继续，否则重定向到登录页
        Map<String, String> query = new HashMap<>();
        query.put("client_id", "2920d118c8dca819b48d345f2236fc247fdeb3888ffae8816ed2bb23f20d5767");
        query.put("client_secret", "76ecc16beb70e5841842a49658445ad501fb715f717cb0213b3027373de60a4a");
        query.put("grant_type", "authorization_code");
        query.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        query.put("code", code);

        //发送 post 请求获取 token
        HttpResponse response = HttpUtils.doPost(
                "https://gitee.com", "/oauth/token", "post", new HashMap<>(), query, new HashMap<>());

        if (response.getStatusLine().getStatusCode() == 200) {
            //2、调用 member 远程接口进行 oauth 登录，登录成功则转发至首页并携带返回用户信息，否则转发至登录页
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, new TypeReference<SocialUser>() {});
            R oauthLogin = memberFeignService.oauth2Login(socialUser);    //远程调用《根据 token 获取用户信息》方法
            //2.1 远程调用成功，返回首页并携带用户信息
            if (oauthLogin.getCode() == 0) {
                MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {});
                log.info("登录成功：用户信息：{}", data.toString());

                //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                //以后浏览器访问哪个网站就会带上这个网站的cookie
                //TODO 1、默认发的令牌。是当前域（所以要解决子域 session 共享问题）
                //TODO 2、使用 JSON 的序列化方式来序列化对象到 Redis 中
                session.setAttribute("loginUser", data);
                return "redirect:http://gulimall.com";
            } else {
                //2.2 否则返回登录页
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            //3、如果获取 token 失败，一样回到登录页
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
